package com.sardine.base.threads.master;

import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CountDownLatch;

/**
 * 北京京东世纪贸易有限公司<br>
 * Created with IntelliJ IDEA.
 * Date:2015/10/1
 * Time:17:30
 *
 * @author daifeng<br>
 *         daifeng@jd.com
 * @since JDK 1.6 <br>
 * Copyright (c) 2015 JD System Incorporated All Rights Reserved.
 */
public abstract class MWorker implements Runnable {
    //任务队列
    protected Queue<Object> workerQueue = new ConcurrentLinkedQueue<Object>();
    //子任务处理结果集
    protected Map<String, Object> resultMap;
    //一个同步辅助类
    protected CountDownLatch downLatch;

    public void setDownLatch(CountDownLatch downLatch) {
        this.downLatch = downLatch;
    }

    public void setWorkerQueue(Queue<Object> workerQueue) {
        this.workerQueue = workerQueue;
    }

    public void setResultMap(Map<String, Object> resultMap) {
        this.resultMap = resultMap;
    }

    /**
     * 子任务处理的逻辑，在子类中实现具体逻辑
     *
     * @param input
     * @return
     */
    public abstract Object handle(Object input);

    @Override
    public void run() {

        while (true) {
            //弹出一个任务
            Object input = workerQueue.poll();
            if (input == null) break;
            try {
                //处理子任务
                Object re = handle(input);
                if (re != null) {
                    resultMap.put(Integer.toString(input.hashCode()), re);
                }
            } finally {
                //结束线程
                downLatch.countDown();
            }
        }

    }
}
